import java.net.Proxy;
import java.util.Map;

import com.game79.musou.webapp.action.ActionBase;

import flex.messaging.io.amf.ASObject;
import flex.messaging.io.amf.client.AMFConnection;
import flex.messaging.io.amf.client.exceptions.ClientStatusException;
import flex.messaging.io.amf.client.exceptions.ServerStatusException;


public class AMFConnectionEntry {
	
	private AMFConnection connection;
	private boolean inited = false;
	
	public void init(Proxy proxy){
		connection = new AMFConnection();
		if(proxy != null){
			connection.setProxy(proxy);
		}
		this.inited = true;
	}
	
	public void destroy(){
		connection.close();
		connection = null;
		inited = false;
	}
	
	public void connect(int server, String sessionId){
		if(!inited){
			System.out.println("Connection not inited!");
		}
		try {
			connection.connect("http://x"+server+".s.jzsg.renren.com/messagebroker/amf");
		} catch (ClientStatusException e) {
			e.printStackTrace();
			return;
		}
		connection.addHttpRequestHeader("Content-type", "application/x-amf");
		connection.addHttpRequestHeader("Cookie", "JSESSIONID="+sessionId);
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> call(String service, ActionBase action){
		try {
			return (Map<String, Object>) connection.call(service, action);
		} catch (ClientStatusException e) {
			e.printStackTrace();
			return null;
		} catch (ServerStatusException e) {
			e.printStackTrace();
			return null;
		}
	}

	public AMFConnection getConnection() {
		return connection;
	}
	public void setConnection(AMFConnection connection) {
		this.connection = connection;
	}
}
